import { getUserPhone } from "@src/api/base";
import router from "@src/router";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import payBehavior from "./payBehavior";
import reservation from "@src/store/reservation";
import {
  creatOrder,
  getAppointmentResourcesDetail,
  getAppointmentShopDetail,
  getGoodsList,
  getPreOrder,
  preOrder,
} from "@src/api/reservation";
import { queryDiscount } from "@src/api/order";
import $math from "@src/common/math";
import {
  RESERVATION_PAY_TYPE,
  RESERVATION_PAY_TYPE_LIST,
  RESERVATION_PAY_TYPE_TEXT,
  ORDER_TYPE,
  DISCOUNT_TYPE,
  DISCOUNT_TYPE_TEXT,
} from "@src/sp-reservation/constant/index.js";
import { handleCheckAllowedPwd } from "@src/common/reservation/config/index.js";
import { getPayChannels } from "@src/common/reservation/config/index.js";
import { isMobile } from "@src/common/validator/rules";
import member from "@src/store/member";
import location from "@src/store/location";
import base from "@src/store/base";
const TITLE_TEXT = {
  0: "确认预约",
  1: "订单详情",
};
Page({
  behaviors: [storeBindingsBehavior, payBehavior],
  storeBindings: [
    {
      store: base,
      fields: ["themeColor", "themeTitleColor", "perms", "businessName"],
    },
    {
      store: reservation,
      fields: ["goodsInfo"],
      actions: ["setSubmitGoodsInfo"],
    },
    {
      store: member,
      fields: ["wxName", "wxHeadImg", "phone", "cardNo"],
      actions: ["initBase", "getBaseInfo"],
    },
    {
      store: location,
      fields: ["latitude", "longitude"],
      actions: ["getLocation", "showAuthTip"],
    },
  ],
  data: {
    loading: false,
    //路由信息
    options: {},
    parseGoodsInfo: {},
    //提交order信息
    params: {
      downName: "",
      downPhone: "",
      pay_type: RESERVATION_PAY_TYPE.ON_LINE,
      customerRemark: "",
      discountInfo: {},
    },
    RESERVATION_PAY_TYPE,
    totalFee: 0, //提交计算总价
    goodPrice: 0, //原始总价
    pay_text: RESERVATION_PAY_TYPE_TEXT[RESERVATION_PAY_TYPE.ON_LINE],
    //优惠券
    isShowCouponSelect: false,
    isHideInput: false,
    couponsList: [],
    DISCOUNT_TYPE,
    DISCOUNT_TYPE_TEXT,
    //商品信息
    //店铺信息
    shopInfo: {},
    //其他信息
    title: "",
    specsTitle: "",
    isSubmit: false,
    payChannels: [],
  },
  onLoad: function (options) {
    wx.showLoading({ title: "加载中" });
    const { title } = options;
    const titleText = TITLE_TEXT[Number(title)] || "确认预约";
    this.setData({
      title: titleText,
      isSubmit: Number(title) === 0,
      options,
    });
    console.log("会员信息", this.data.phone);
    // this.fetchData();
  },

  onPullDownRefresh() {
    this.setData({ loading: true });
    wx.showLoading({ title: "加载中" });
    this.fetchData();
    this.getAccountInfo();
  },

  onLogin() {
    this.getLocation(true)
      .then((res) => {
        if (this.data.options.shopId) {
          this.setData({ latitude: res.latitude, longitude: res.longitude });
          this.fetchData();
          this.getAccountInfo();
        }
      })
      .catch((res) => {
        if (this.data.options.shopId) {
          this.fetchData();
          this.initBaseInfo();
          this.getAccountInfo();
        }
      });
  },
  initBaseInfo() {
    this.initBase();
    this.getBaseInfo();
  },
  async fetchData() {
    this.initBaseInfo();
    let params = JSON.parse(JSON.stringify(this.data.params));
    params.downName = this.data.wxName;
    params.downPhone = this.data.phone;
    this.setData({
      params,
    });
    const {
      options: { shopId },
    } = this.data;
    const { goodsInfo } = this.data;
    const parseGoodsInfo = JSON.parse(goodsInfo);
    //获取门店信息
    const { code, data: shopData } = await getAppointmentShopDetail({ shopId });
    if (code === 0) {
      this.setData({
        shopInfo: shopData,
        parseGoodsInfo,
      });
      const { skuInfo, categoryInfo, specs } = JSON.parse(goodsInfo);
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
      wx.hideLoading();
      if (specs?.length > 0) {
        const specsStr = specs.map((v) => v.title).join(",");
        const len = specsStr.length;
        const specsTitle = specsStr.slice(0, len);
        this.setData({
          specsTitle,
        });
      }
      //新增需求 ---start 商品/资源信息实时更新 ---start
      if (categoryInfo.id) {
        const { code, data } = await getAppointmentResourcesDetail({
          categoryId: categoryInfo.id,
        });
        if (code === 0) {
          parseGoodsInfo.categoryInfo.price = data.price || 0;
          parseGoodsInfo.categoryInfo.levelName = data.levelName || 0;
          parseGoodsInfo.categoryInfo.name = data.name || 0;
          parseGoodsInfo.categoryInfo.a = 1;
          console.log("资源信息===", parseGoodsInfo.categoryInfo);
        }
      }

      const {
        skuInfo: { goodsSerial, skuId },
        categoryInfo: { planId },
      } = parseGoodsInfo;
      const {
        shopInfoResp: { shopId, shopConfigId },
      } = shopData;
      const { code: goodsCode, data: goodsData } = await getGoodsList({
        goodsSerial,
        shopConfigId,
        planId,
        shopId,
      });
      if (goodsCode === 0) {
        const skus =
          goodsData.goodsPageData.skuInfo.skuList.filter(
            (v) => v.skuId === skuId
          )[0] || {};
        parseGoodsInfo.skuInfo.price = skus.price || 0;
        parseGoodsInfo.categoryInfo.serviceDuration =
          goodsData.planInfo.serviceDuration || 0;
        parseGoodsInfo.skuInfo.title = goodsData.goodsPageData.goods.title;
        parseGoodsInfo.skuInfo.a = 2;
        console.log("商品信息===", parseGoodsInfo.skuInfo);
        this.setSubmitGoodsInfo(JSON.stringify(parseGoodsInfo));
      }

      //新增需求 ---end 商品/资源信息实时更新 ---end

      wx.nextTick(() => {
        const { skuInfo, categoryInfo } = JSON.parse(this.data.goodsInfo);
        console.log("提交信息整合", JSON.parse(this.data.goodsInfo));
        this.setData({
          parseGoodsInfo: JSON.parse(this.data.goodsInfo),
          goodPrice: (
            (skuInfo.price + (categoryInfo.price || 0)) /
            100
          ).toFixed(2),
          totalFee: ((skuInfo.price + (categoryInfo.price || 0)) / 100).toFixed(
            2
          ),
        });
        this.initDiscount();
      });
    }
  },
  async initDiscount() {
    const { goodsInfo } = this.data;
    const { skuInfo, categoryInfo } = JSON.parse(goodsInfo);
    //获取优惠信息
    let discountData = {
      orderType: ORDER_TYPE.APPOINTMENT,
      shopId: this.data.shopInfo.shopInfoResp.shopId,
      tradeFee: $math.mul(skuInfo.price + (categoryInfo.price || 0), 1, 0),
      // joinMercNo:$cache.get('themeConfig-mall').mercNo
    };
    const { code: disCode, data: disData } = await queryDiscount(discountData);
    if (disCode === 0) {
      console.log("优惠列表", disData);
      disData.map((v, index) => {
        v.tempId = index;
        return v;
      });
      const couponsList = disData?.filter(
        (v) => v.discountType !== DISCOUNT_TYPE.CARD
      );
      if (couponsList.length > 0) {
        const tempCouponsList = couponsList.sort((a, b) => {
          return b.discountFee - a.discountFee;
        });
        if (this.data.params.pay_type === RESERVATION_PAY_TYPE.ON_LINE) {
          this.handleSelectCoupon({ detail: tempCouponsList[0] });
        }
      } else {
        this.handleSelectCoupon({ detail: {} });
      }
      this.setData({
        params: {
          ...this.data.params,
        },
        couponsList,
      });
    }
  },
  handleOpenMap() {
    console.log("点击底图");
    const {
      shopInfoResp: { latitude, longitude, address, shopName },
    } = this.data.shopInfo;
    wx.openLocation({
      latitude,
      longitude,
      name: shopName,
      address,
    });
  },
  bindKeyInputDownName(e) {
    const downName = e.detail.value;
    this.setData({
      params: {
        ...this.data.params,
        downName,
      },
    });
  },
  bindKeyInputDownPhone(e) {
    const phone = e.detail.value;
    this.setData({
      params: {
        ...this.data.params,
        downPhone: phone,
      },
    });
  },
  bindKeyBlurDownPhone() {
    setTimeout(() => {
      const { downPhone } = JSON.parse(JSON.stringify(this.data.params));
      if (!downPhone) return;
      const isMobilePhone = isMobile(downPhone, "请输入有效手机号");
      const params = Object.assign({}, this.data.params);
      params.downPhone = "";
      if (isMobilePhone) {
        this.setData({ params, isHideInput: false });
        wx.hideLoading();
        return wx.showToast({
          title: "请输入有效手机号",
          icon: "none",
          duration: 2500,
        });
      }
    }, 500);
  },
  bindKeyInputRemark(e) {
    this.setData({
      params: {
        ...this.data.params,
        customerRemark: e.detail.value,
        remark: e.detail.value,
      },
    });
  },
  onClickClearDownPhone() {
    let params = Object.assign({}, this.data.params);
    params.downPhone = "";
    this.setData({
      params,
    });
  },
  onClickClearDownName() {
    let params = Object.assign({}, this.data.params);
    params.downName = "";
    this.setData({
      params,
    });
  },
  getPhoneNumber(e) {
    if (!e.detail.iv) {
      return;
    }
    let data = {
      ivStr: e.detail.iv,
      encryptedData: e.detail.encryptedData,
    };
    getUserPhone(data).then((res) => {
      if (res.code === 0) {
        this.setData({ params: { ...this.data.params, downPhone: res.data } });
      } else {
        wx.showToast({
          title: "手机号获取失败，请重试",
          icon: "none",
          duration: 3000,
        });
      }
    });
  },
  getUserInfo() {
    wx.getUserProfile({
      desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        const {
          userInfo: { nickName },
        } = res;
        this.setData({
          params: {
            ...this.data.params,
            downName: nickName,
          },
        });
      },
    });
    // const {errMsg,}=e.
  },
  handleToMap() {
    const {
      shopInfoResp: { latitude, longitude, shopName, address },
    } = this.data.shopInfo;
    wx.openLocation({
      latitude,
      longitude,
      name: shopName,
      address,
      scale: 18,
    });
  },
  handleChoosePayType() {
    wx.showActionSheet({
      itemList: RESERVATION_PAY_TYPE_LIST.map((v) => v.label),
      success: (e) => {
        const { errMsg, tapIndex } = e;

        if (errMsg === "showActionSheet:ok") {
          const pay_type =
            tapIndex === 0
              ? RESERVATION_PAY_TYPE.ON_LINE
              : RESERVATION_PAY_TYPE.SHOP_PAY;
          //到店支付不支持优惠
          this.setData({
            params: {
              ...this.data.params,
              pay_type,
              discountInfo:
                pay_type === RESERVATION_PAY_TYPE.SHOP_PAY
                  ? {}
                  : this.data.couponsList[0],
            },
            totalFee: Number(this.data.goodPrice),
            pay_text: RESERVATION_PAY_TYPE_LIST.filter(
              (v) => v.value === pay_type
            )[0]?.label,
          });
          // this.setData({
          //   params: {
          //     ...this.data.params,
          //     pay_type,
          //   },
          //   pay_text: RESERVATION_PAY_TYPE_LIST.filter(
          //     (v) => v.value === pay_type
          //   )[0]?.label,
          // });
          wx.nextTick(() => {
            this.handleSelectCoupon({ detail: this.data.couponsList[0] || {} });
          });
        }
        console.log(e);
      },
    });
  },
  async handleBindPhonePay(e = 0) {
    console.log("支付", e);
    if (!e.detail.iv) {
      return;
    }
    let phoneData = {
      ivStr: e.detail.iv,
      encryptedData: e.detail.encryptedData,
    };
    getUserPhone(phoneData).then(async (res) => {
      if (res.code === 0) {
        const readonlyDownPhone = res.data;
        await this.handleNextPayWithNoMember(readonlyDownPhone);
        // this.setData({ params: { ...this.data.params, downPhone: res.data } });
      }
    });
  },
  async handleNextPayWithNoMember(readonlyDownPhone) {
    console.log("点击");
    // this.handleShowSelectTime();
    const { goodsInfo, params, goodPrice, shopInfo, accountPayRule } =
      JSON.parse(JSON.stringify(this.data));
    const parseGoodsInfo = JSON.parse(goodsInfo);
    //新增初始化会员密码操作
    const initialed = await handleCheckAllowedPwd(goodPrice, accountPayRule);
    if (!initialed) return;
    wx.showLoading({ title: "支付唤起中" });
    const { productId, id, title, type, price, imgUrl, skuId } =
      parseGoodsInfo.skuInfo;
    const { specs, categoryInfo, dateTimeInfo } = parseGoodsInfo;
    const goodItem = {
      goodsId: id,
      title,
      // skuInfoList: specs.map((v) => {
      //   v.skuId = v.id;
      //   v.skuName = v.title;
      //   return v;
      // }),
      skuInfoList: [
        {
          skuId,
          skuName: title,
          attrNames: specs,
        },
      ],
      goodsType: type,
      price,
      coverImg: imgUrl,
    };
    const preOrderInfo = {
      categoryVOS: [
        {
          categoryId: categoryInfo.id || 0,
          id: categoryInfo.id || 0,
          categoryName: categoryInfo.name || "",
          categoryLevelName: categoryInfo.levelName || "",
          categoryLevelId:
            categoryInfo.levelId !== null && categoryInfo.levelId !== undefined
              ? categoryInfo.levelId
              : "",
        },
      ],
      planVO: {
        id: categoryInfo.planId,
      },
      paymentType: params.pay_type,
      discount: { discountInfo: params.discountInfo },
      downName: this.data.wxName,
      downPhone: readonlyDownPhone,
      preName: params.downName,
      prePhone: params.downPhone,
      goodItem,
      remark: params.customerRemark,
      customerRemark: params.customerRemark,
      shopId: shopInfo.shopInfoResp.shopId,
      shopName: shopInfo.shopInfoResp.shopName,
      preDate: `${dateTimeInfo.date.value} ${dateTimeInfo.time.time}`,
      preTime: categoryInfo.serviceDuration,
      serviceDuration: categoryInfo.serviceDuration,
      time: `${dateTimeInfo.time.time}`,
      totalFee: $math.mul(goodPrice, 100, 0),
      // totalFee: Number(goodPrice) * 100,
    };
    if (!preOrderInfo.preName) {
      wx.hideLoading();
      wx.showToast({
        title: "请填写预约人姓名",
        icon: "none",
        duration: 2000,
      });
      this.setData({
        isHideInput: false,
      });
      return;
    }
    if (!preOrderInfo.prePhone) {
      wx.hideLoading();
      wx.showToast({
        title: "请填写预约人联系方式",
        icon: "none",
        duration: 2500,
      });
      this.setData({
        isHideInput: false,
      });
      return;
    }
    const isMobilePhone = isMobile(preOrderInfo.prePhone, "联系方式不正确");
    if (isMobilePhone) {
      this.setData({
        isHideInput: false,
      });
      wx.hideLoading();
      return wx.showToast({
        title: "联系方式不正确",
        icon: "none",
        duration: 2500,
      });
    }
    console.log("正在支付", parseGoodsInfo, params);
    console.log("支付参数", preOrderInfo);
    const { code, data } = await preOrder(preOrderInfo);
    if (code === 0) {
      const { preNo } = data;
      preOrderInfo.preNo = preNo;
      getPreOrder({
        preNo,
      })
        .then((preRes) => {
          const { code, data } = preRes;
          if (code === 0) {
            const { orderPayInfo } = data;
            const payChannels = getPayChannels(orderPayInfo.payChannels);
            this.setData({
              isHideInput: true,
              payChannels,
            });
            console.log("支付方式", payChannels);
            this.handleCreatOrder(preOrderInfo);
          }
        })
        .catch((err) => {
          wx.showToast({
            title: "获取支付方式失败",
            icon: "none",
          });
        });
    }
  },
  async handlePay() {
    const { goodsInfo, params, goodPrice, shopInfo, accountPayRule, phone } =
      JSON.parse(JSON.stringify(this.data));
    const parseGoodsInfo = JSON.parse(goodsInfo);
    const readonlyDownPhone = phone;
    //新增初始化会员密码操作
    const initialed = await handleCheckAllowedPwd(goodPrice, accountPayRule);
    if (!initialed) return;
    wx.showLoading({ title: "支付唤起中" });
    const { productId, id, title, type, price, imgUrl, skuId } =
      parseGoodsInfo.skuInfo;
    const { specs, categoryInfo, dateTimeInfo } = parseGoodsInfo;
    const goodItem = {
      goodsId: id,
      title,
      skuInfoList: [
        {
          skuId,
          skuName: title,
          attrNames: specs,
        },
      ],
      goodsType: type,
      price,
      coverImg: imgUrl,
    };
    const preOrderInfo = {
      categoryVOS: [
        {
          categoryId: categoryInfo.id || 0,
          id: categoryInfo.id || 0,
          categoryName: categoryInfo.name || "",
          categoryLevelName: categoryInfo.levelName || "",
          categoryLevelId:
            categoryInfo.levelId !== null && categoryInfo.levelId !== undefined
              ? categoryInfo.levelId
              : "",
        },
      ],
      planVO: {
        id: categoryInfo.planId,
      },
      paymentType: params.pay_type,
      discount: { discountInfo: params.discountInfo },
      downName: this.data.wxName,
      downPhone: readonlyDownPhone || "",
      preName: params.downName,
      prePhone: params.downPhone,
      goodItem,
      remark: params.customerRemark,
      customerRemark: params.customerRemark,
      shopId: shopInfo.shopInfoResp.shopId,
      shopName: shopInfo.shopInfoResp.shopName,
      preDate: `${dateTimeInfo.date.value} ${dateTimeInfo.time.time}`,
      preTime: categoryInfo.serviceDuration,
      serviceDuration: categoryInfo.serviceDuration,
      time: `${dateTimeInfo.time.time}`,
      totalFee: $math.mul(goodPrice, 100, 0),
      // totalFee: Number(goodPrice) * 100,
    };
    if (!preOrderInfo.preName) {
      wx.hideLoading();
      wx.showToast({
        title: "请填写预约人姓名",
        icon: "none",
        duration: 2000,
      });
      this.setData({
        isHideInput: false,
      });
      return;
    }
    if (!preOrderInfo.prePhone) {
      wx.hideLoading();
      wx.showToast({
        title: "请填写预约人联系方式",
        icon: "none",
        duration: 2500,
      });
      this.setData({
        isHideInput: false,
      });
      return;
    }
    const isMobilePhone = isMobile(preOrderInfo.prePhone, "联系方式不正确");
    if (isMobilePhone) {
      this.setData({
        isHideInput: false,
      });
      wx.hideLoading();
      return wx.showToast({
        title: "联系方式不正确",
        icon: "none",
        duration: 2500,
      });
    }
    console.log("正在支付", parseGoodsInfo, params);
    console.log("支付参数", preOrderInfo);
    const { code, data } = await preOrder(preOrderInfo);
    if (code === 0) {
      const { preNo } = data;
      preOrderInfo.preNo = preNo;
      getPreOrder({
        preNo,
      })
        .then((preRes) => {
          const { code, data } = preRes;
          if (code === 0) {
            const { orderPayInfo } = data;
            const payChannels = getPayChannels(orderPayInfo.payChannels);
            this.setData({
              isHideInput: true,
              payChannels,
            });
            console.log("支付方式", payChannels);
            this.handleCreatOrder(preOrderInfo);
          }
        })
        .catch((err) => {
          wx.showToast({
            title: "获取支付方式失败",
            icon: "none",
          });
        });
    }
  },
  handleBindMember() {
    //绑定会员卡
    wx.showModal({
      title: "提示",
      content: "是否开通会员卡",
      showCancel: true,
      success: (res) => {
        if (res.confirm) {
          router.push({
            name: "indexChooseCard",
          });
        }
      },
    });
  },
  handleCreatOrder(preOrderInfo) {
    const {
      params: { pay_type },
      shopInfo,
    } = this.data;
    creatOrder(preOrderInfo)
      .then((res) => {
        wx.hideLoading();
        console.log("创建订单结果", res);
        if (res.code === 0) {
          const orderData = res.data;
          if (pay_type === RESERVATION_PAY_TYPE.ON_LINE) {
            //在线支付
            // maxPayLatency: 300
            // orderNo: "30050788016584315784"
            // payFee: 101
            this.toPay(res.data)
              .then((res) => {
                this.setData({
                  isHideInput: false,
                });
                console.log("支付成功", res);
                router.redirectTo({
                  // name: "reservation/reservation_order_detail",
                  name: "reservation/reservation_success",
                  params: {
                    ...orderData,
                    shopId: shopInfo.shopInfoResp.shopId,
                  },
                });
              })
              .catch((err) => {
                this.setData({
                  isHideInput: false,
                });
                if (err?.data?.msg) {
                  wx.showToast({
                    title: err?.data?.msg,
                    icon: "none",
                    duration: 2500,
                  });
                }
                setTimeout(() => {
                  router.redirectTo({
                    name: "reservation/reservation_order_detail",
                    params: {
                      ...orderData,
                      shopId: shopInfo.shopInfoResp.shopId,
                    },
                  });
                }, 500);
                console.log("支付失败", err);
              });
          } else {
            this.setData({
              isHideInput: false,
            });
            router.redirectTo({
              name: "reservation/reservation_success",
              params: {
                ...orderData,
                shopId: shopInfo.shopInfoResp.shopId,
              },
            });
          }
        } else {
          wx.hideLoading();
          this.setData({
            isHideInput: false,
          });
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2500,
          });
        }
      })
      .catch((err) => {
        const {
          data: { msg },
        } = err;
        wx.hideLoading();
        this.setData({
          isHideInput: false,
        });
        wx.showToast({
          title: msg,
          icon: "none",
          duration: 2500,
        });
      });
  },
  //优惠券弹窗
  handleShowCouponSelect() {
    if (this.data.couponsList.length === 0) return;
    this.setData({
      isShowCouponSelect: !this.data.isShowCouponSelect,
    });
  },
  handleSelectCoupon(e = {}) {
    //到店支付不选优惠判断
    if (this.data.params.pay_type === RESERVATION_PAY_TYPE.SHOP_PAY) return;
    const { detail } = e;
    const parseGoodsInfo = JSON.parse(this.data.goodsInfo);
    const { skuInfo, categoryInfo } = parseGoodsInfo;
    this.setData({
      params: {
        ...this.data.params,
        discountInfo: detail,
      },
      totalFee: (
        (skuInfo.price +
          (categoryInfo.price || 0) -
          (detail.discountFee || 0)) /
        100
      ).toFixed(2),
    });
    this.setData({
      isShowCouponSelect: false,
    });
  },
});
